//
//  RHMePriceSetVC.m
//  RuiHeApp
//
//  Created by Yan Chen on 2025/1/22.
//

#import "RHMePriceSetVC.h"
#import "RHMePriceCityCell.h"
#import "RHMePriceCell.h"
#import "RHMePriceTimeRangeCell.h"
#import "RHPlantModel.h"
#import "RHMePolicyAddTipsView.h"
#import "RHMeElectricPricePatternModel.h"
#import "RHMePricePatternVC.h"
#import "RHChoiceCityView.h"

@interface RHMePriceSetVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSArray *dataArr;

@property (nonatomic ,strong) NSMutableArray *timeArr;

@property (nonatomic ,strong) NSDictionary *addressParaDic;
@end

@implementation RHMePriceSetVC


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"电价设置".rh_localized;
    self.view.backgroundColor = CFTabViewBgColor;
    [self createData];
    [self setupUI];
    [self getelectricityPriceDetail];
}

- (void)setupUI{
    kWeakSelf;
    self.timeArr = [NSMutableArray array];
    UIBarButtonItem *rightItem = [UIBarButtonItem itemWithTitle:@"使用模板".rh_localized titleColor:CMainColorGreen titleFont:kSYSTEMFONT(14) Target:self Seletor:@selector(patternAction)];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    QMUIButton *addBtn = [QMUIButton buttonWithTitle:@"添加到模板".rh_localized titleColor:UIColor.whiteColor titleFont:kBOLDSYSTEMFONT(20)];
    [addBtn setBackgroundColor:CMainColorGreen];
    [addBtn setCornerRadius:8];
    [self.view addSubview:addBtn];
    [addBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_offset(kSafe_bottom>0?-kSafe_bottom:-15);
        make.left.mas_offset(15);
        make.height.offset(50);
        make.width.equalTo(self.view).multipliedBy(0.6);
    }];
    
    QMUIButton *saveBtn = [QMUIButton buttonWithTitle:@"保存".rh_localized titleColor:CMainColorGreen titleFont:kBOLDSYSTEMFONT(18)];
    [saveBtn setCornerRadius:8];
    [saveBtn setQmui_borderColor:CMainColorGreen];
    [saveBtn setQmui_borderWidth:1];
    [saveBtn setQmui_borderPosition:QMUIViewBorderPositionTop|QMUIViewBorderPositionLeft|QMUIViewBorderPositionRight|QMUIViewBorderPositionBottom ];
    [saveBtn setBackgroundColor:kCOLOR_HEX_A(@"#05C79D", 0.1)];
    
    [self.view addSubview:saveBtn];
    [saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(addBtn.mas_right).offset(15);
        make.right.mas_offset(-15);
        make.height.centerY.equalTo(addBtn);
    }];
    
    [[addBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf showPopView];
    }];
    
    [[saveBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf savePricePattern];
    }];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:kCOLOR_HEX(@"#F0F5FF")];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setSeparatorColor:UIColor.clearColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHMePriceCityCell class] forCellReuseIdentifier:@"RHMePriceCityCell"];
    [_tableView registerClass:[RHMePriceCell class] forCellReuseIdentifier:@"RHMePriceCell"];
    [_tableView registerClass:[RHMePriceTimeRangeCell class] forCellReuseIdentifier:@"RHMePriceTimeRangeCell"];
    [self.view addSubview:_tableView];
   
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.bottom.equalTo(addBtn.mas_top).offset(-15);
        make.top.mas_offset(0);
    }];

}

#pragma mark ------ 使用模板
-(void)patternAction
{
    kWeakSelf;
    RHMePricePatternVC *patternVC = [[RHMePricePatternVC alloc]init];
    patternVC.usePatternBlock = ^(RHPatternModel * pattern) {
        NSDictionary *dic = [(NSObject*)pattern yy_modelToJSONObject];
        NSString *configString = dic[@"configJson"];
        NSArray *arr = [configString jsonStringToArray];
        weakSelf.timeArr = arr.mutableCopy;
        [weakSelf readData:dic];
    };
    [self.navigationController pushViewController:patternVC animated:YES];
}

-(void)showPopView
{
    kWeakSelf;
    
    __block BOOL checkOK = YES;
    [self.dataArr enumerateObjectsUsingBlock:^(NSArray*  _Nonnull sectionArr, NSUInteger idx, BOOL * _Nonnull stop_section) {
        [sectionArr enumerateObjectsUsingBlock:^(RHMeElectricPricePatternModel*  _Nonnull rowModel, NSUInteger idx, BOOL * _Nonnull stop) {
           
            if (rowModel.isRequired&&rowModel.content.length == 0) {
                [QMUITips showInfo:rowModel.placeHolder];
                checkOK = NO;
                *stop_section = YES;
                *stop = YES;
                return;
            }
        }];
    }];
    
    if (checkOK == NO) {
        return;
    }
    
    //时段必须全部选满
    if (self.timeArr.count<48) {
        [QMUITips showInfo:@"时段必须选满".rh_localized];
        checkOK = NO;
        return;
    }
    [self.timeArr enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull dic, NSUInteger idx, BOOL * _Nonnull stop) {
        if (dic.allKeys.count<2) {
            [QMUITips showInfo:@"时段必须选满".rh_localized];
            checkOK = NO;
            *stop = YES;
        }
    }];
    
    if (checkOK == NO) {
        return;
    }
    
    RHMePolicyAddTipsView *tipView = [[RHMePolicyAddTipsView alloc]init];
    [tipView showWithTitle:@"添加电价模板".rh_localized detail:@"电价模板名称".rh_localized];
    tipView.finishBlock = ^(NSString * _Nonnull patternName) {
        [weakSelf addPricePattern:patternName];
    };
}

#pragma mark ------- 添加电价模版 -------
-(void)addPricePattern:(NSString*)paternName
{
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:@(self.plantModel.plant_id) forKey:@"plantId"];
    [para setObject:paternName forKey:@"templateName"];
    __block BOOL checkOK = YES;
    [self.dataArr enumerateObjectsUsingBlock:^(NSArray*  _Nonnull sectionArr, NSUInteger idx, BOOL * _Nonnull stop) {
        [sectionArr enumerateObjectsUsingBlock:^(RHMeElectricPricePatternModel*  _Nonnull rowModel, NSUInteger idx, BOOL * _Nonnull stop) {
            if (rowModel.content.length>0) {
                [para setObject:rowModel.content forKey:rowModel.key];
            }else{
                if (rowModel.isRequired) {
                    [QMUITips showInfo:rowModel.placeHolder];
                    checkOK = NO;
                    *stop = YES;
                }
            }
            
        }];
    }];
    if (checkOK == NO) {
        return;
    }
    //时段
    NSString *timeJsonString = [self.timeArr yy_modelToJSONString];
    [para setObject:ValidNullData(timeJsonString) forKey:@"configJson"];
    //地址id
    if (self.addressDic) {
        [para addEntriesFromDictionary:self.addressDic];
    }
    [QMUITips showLoadingInView:kAppWindow];
    [BaseModel startWithCompletionAPIKey:H_addElectricityPricePattern argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            [QMUITips showSucceed:@"成功".rh_localized];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

#pragma mark ------- 保存(修改)电价配置 -------
-(void)savePricePattern
{
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:@(self.plantModel.plant_id) forKey:@"plantId"];
   
    __block BOOL checkOK = YES;
    [self.dataArr enumerateObjectsUsingBlock:^(NSArray*  _Nonnull sectionArr, NSUInteger idx, BOOL * _Nonnull stop) {
        [sectionArr enumerateObjectsUsingBlock:^(RHMeElectricPricePatternModel*  _Nonnull rowModel, NSUInteger idx, BOOL * _Nonnull stop) {
            if (rowModel.content.length>0) {
                [para setObject:rowModel.content forKey:rowModel.key];
            }else{
                if (rowModel.isRequired) {
                    [QMUITips showInfo:rowModel.placeHolder];
                    checkOK = NO;
                    *stop = YES;
                }
            }
            
        }];
    }];
    if (checkOK == NO) {
        return;
    }
    //时段
    NSString *timeJsonString = [self.timeArr yy_modelToJSONString];
    [para setObject:ValidNullData(timeJsonString) forKey:@"configJson"];
    //地址id
    if (self.addressParaDic) {
        [para addEntriesFromDictionary:self.addressParaDic];
    }
 
    [QMUITips showLoadingInView:kAppWindow];
    [BaseModel startWithCompletionAPIKey:H_saveElectricityPricePattern argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            [QMUITips showSucceed:@"成功".rh_localized];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}
#pragma mark ------- 根据电站获取电价配置 -------
-(void)getelectricityPriceDetail
{
    NSString *url = [NSString stringWithFormat:@"%@/%ld",H_electricityPriceDetail,self.plantModel.plant_id];
    [BaseModel startGetWithCompletionAPIKey:url argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            NSString *configString = request.responseJSONObject[@"data"][@"configJson"];
            NSArray *arr = [configString jsonStringToArray];
            self.timeArr = arr.mutableCopy;
            [self readData:request.responseJSONObject[@"data"]];
            
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

-(void)readData:(NSDictionary*)dic
{
    [self.dataArr enumerateObjectsUsingBlock:^(NSArray*  _Nonnull sectionArr, NSUInteger idx, BOOL * _Nonnull stop) {
        [sectionArr enumerateObjectsUsingBlock:^(RHMeElectricPricePatternModel*  _Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
            [model readDic:dic];
            //城市不处理,从上一页面来,不可编辑
//            if ([model.tag isEqualToString:@"pattern_city"]) {
//                NSMutableString *address = [NSMutableString string];
//                NSMutableDictionary *addressParaDic = [NSMutableDictionary dictionary];
//                if (dic[@"countryName"]) {
//                    [address appendFormat:@"/%@",dic[@"countryName"]];
//                    [addressParaDic setObject:dic[@"countryId"] forKey:@"countryId"];
//                    [addressParaDic setObject:dic[@"countryName"] forKey:@"countryName"];
//                }
//                if (dic[@"stateName"]) {
//                    [address appendFormat:@"/%@",dic[@"stateName"]];
//                    [addressParaDic setObject:dic[@"stateId"] forKey:@"stateId"];
//                    [addressParaDic setObject:dic[@"stateName"] forKey:@"stateName"];
//                }
//                if (dic[@"cityName"]) {
//                    [address appendFormat:@"/%@",dic[@"cityName"]];
//                    [addressParaDic setObject:dic[@"cityId"] forKey:@"cityId"];
//                    [addressParaDic setObject:dic[@"cityName"] forKey:@"cityName"];
//                }
//                self.addressParaDic = addressParaDic.copy;
//                model.content = address.copy;
//            }
        }];
        
    }];
    [self.tableView reloadData];
}

-(void)selectCity:(RHMeElectricPricePatternModel*)model
{
    kWeakSelf;
    RHChoiceCityView *cityView = [[RHChoiceCityView alloc]init];
    cityView.choiceResultBlock = ^(NSString * _Nonnull address,NSDictionary *paraDic) {
        model.content = address;
        weakSelf.addressParaDic = paraDic;
        [weakSelf.tableView reloadData];
    };
    [cityView showAnimation];
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 15;
    }
    if (section ==1 || section == 2) {
        return 55;
    }
    return 15;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section ==1 || section == 2) {
        UIView *headerView = kView;
        UIView *bgView = kView;
        [headerView addSubview:bgView];
        bgView.backgroundColor = UIColor.whiteColor;
        [bgView roundBorder:8 width:1 color:kBorderColor RectCorners:QMUIViewBorderPositionLeft|QMUIViewBorderPositionTop|QMUIViewBorderPositionRight];
        bgView.layer.qmui_maskedCorners = QMUILayerMinXMinYCorner|QMUILayerMaxXMinYCorner;
        [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_offset(15);
            make.left.mas_offset(15);
            make.right.mas_offset(-15);
            make.bottom.mas_offset(0);
        }];
        
        QMUILabel *titleLab = [QMUILabel labelWithText:section==1?@"充电电价".rh_localized:@"放电电价".rh_localized font:kBOLDSYSTEMFONT(16) textColor:kCOLOR_HEX(@"#303133")];
        [bgView addSubview:titleLab];
        [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(15);
            make.centerY.mas_offset(0);
        }];
        [headerView addSubview:bgView];
        
        return headerView;
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return self.dataArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   
    NSArray *sectionArr = [self.dataArr safeObjectAtIndex:section];
    return sectionArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    kWeakSelf;
    NSArray *sectionArr = [self.dataArr safeObjectAtIndex:indexPath.section];
    RHMeElectricPricePatternModel *model = [sectionArr safeObjectAtIndex:indexPath.row];
    if ([model.tag isEqualToString:@"pattern_city"]) {//城市
        RHMePriceCityCell *policyCell = [tableView dequeueReusableCellWithIdentifier:@"RHMePriceCityCell"];
        policyCell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        policyCell.model = model;
        return policyCell;
    }else if([model.tag isEqualToString:@"pattern_time"]){//时段
        RHMePriceTimeRangeCell *timeCell = [tableView dequeueReusableCellWithIdentifier:@"RHMePriceTimeRangeCell"];
        timeCell.selectionStyle = UITableViewCellSelectionStyleNone;
        timeCell.timeArr = self.timeArr;
        timeCell.updateTimeArr = ^(NSMutableArray * _Nonnull timeArr) {
            weakSelf.timeArr = timeArr;
        };
        return timeCell;
    }else if([model.tag isEqualToString:@"pattern_price"]){//电价
        RHMePriceCell *priceCell = [tableView dequeueReusableCellWithIdentifier:@"RHMePriceCell"];
        priceCell.model = model;
        priceCell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        if (indexPath.row == sectionArr.count-1) {
            [priceCell.bgView setBottomBorder];
        }else{
            [priceCell.bgView setMiddleBorder];
        }
        return priceCell;
    }
    return [UITableViewCell new];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *sectionArr = [self.dataArr safeObjectAtIndex:indexPath.section];
    RHMeElectricPricePatternModel *model = [sectionArr safeObjectAtIndex:indexPath.row];
    if ([model.tag isEqualToString:@"pattern_city"]) {
        //不可选择
//        [self selectCity:model];
    }
}

-(void)createData
{
    NSString *city = @"";
    if (self.addressDic[@"cityName"]) {
        city = self.addressDic[@"cityName"];
    }else if(self.addressDic[@"stateName"]){
        city = self.addressDic[@"stateName"];
    }
    NSArray *datas = @[
        @[
            @{@"title":@"电站城市".rh_localized,
              @"placeHolder":@"请输入城市名称".rh_localized,
              @"isRequired":@(1),
              @"tag":@"pattern_city",
              @"key":@"city",
              @"content":city
            }
        ],
        @[
            @{@"title":@"尖时电价".rh_localized,
              @"placeHolder":@"请输入充电尖时电价".rh_localized,
              @"isRequired":@(1),
              @"tag":@"pattern_price",
              @"key":@"chargeTip"
            },
            @{@"title":@"峰时电价".rh_localized,
              @"placeHolder":@"请输入充电峰时电价".rh_localized,
              @"isRequired":@(1),
              @"tag":@"pattern_price",
              @"key":@"chargePeak"
            },
            @{@"title":@"平时电价".rh_localized,
              @"placeHolder":@"请输入充电平时电价".rh_localized,
              @"isRequired":@(1),
              @"tag":@"pattern_price",
              @"key":@"chargeFlat"
            },
            @{@"title":@"谷时电价".rh_localized,
              @"placeHolder":@"请输入充电谷时电价".rh_localized,
              @"isRequired":@(1),
              @"tag":@"pattern_price",
              @"key":@"chargeValley"
            }
        ],
        @[
            @{@"title":@"尖时电价".rh_localized,
              @"placeHolder":@"请输入放电尖时电价".rh_localized,
              @"isRequired":@(1),
              @"tag":@"pattern_price",
              @"key":@"dischargeTip"
            },
            @{@"title":@"峰时电价".rh_localized,
              @"placeHolder":@"请输入放电峰时电价".rh_localized,
              @"isRequired":@(1),
              @"tag":@"pattern_price",
              @"key":@"dischargePeak"
            },
            @{@"title":@"平时电价".rh_localized,
              @"placeHolder":@"请输入放电平时电价".rh_localized,
              @"isRequired":@(1),
              @"tag":@"pattern_price",
              @"key":@"dischargeFlat"
            },
            @{@"title":@"谷时电价".rh_localized,
              @"placeHolder":@"请输入放电谷时电价".rh_localized,
              @"isRequired":@(1),
              @"tag":@"pattern_price",
              @"key":@"dischargeValley"
            }
        ],
        @[
            @{@"title":@"时段设置".rh_localized,
              @"isRequired":@(0),
              @"tag":@"pattern_time",
              @"key":@"configJson"
            }
        ]
        
    ];
    
    NSMutableArray *mtbArr = [NSMutableArray array];
    [datas enumerateObjectsUsingBlock:^(NSArray*  _Nonnull arr, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableArray *rows = [NSMutableArray array];
        [arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            RHMeElectricPricePatternModel *model = [RHMeElectricPricePatternModel yy_modelWithDictionary:obj];
            [rows addObject:model];
        }];
        [mtbArr addObject:rows.copy];
    }];
    
    self.dataArr = mtbArr.copy;
    
    
}

@end
